import re

from flask import Blueprint, request, jsonify
from conf.comm import sqlalchemy_context
from database import *
import json
from werkzeug.security import generate_password_hash

# 蓝图初始化
bp_users = Blueprint('users', __name__)


# 注册功能实现
@bp_users.route('/reg', methods=['POST'])
@sqlalchemy_context()
def reg():
    data = request.data
    # 获取用户输入
    if not data:
        data = request.form
    else:
        data = json.loads(data)
    # 有效性验证
    reg = re.match('^1[3-9]\d{9}$', str(data['mobile']))
    if not reg:
        return jsonify({"code": 10012, 'mes': '手机号不合法'})

    # 构造user
    try:
        user = User(username=data['username'], password=generate_password_hash(data['password']), mobile=data['mobile'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'code': 200})
    except:
        return jsonify({'code': 10010})